from django.shortcuts import render
from  QQLoginTool.QQtool import OAuthQQ
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings  #setting获取配置文件的所有属性
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
# Create your views here.
#
#
#构造跳转连接
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from oauth.serializers import QQAuthUserSerializer


class QQAuthURLView(APIView):

    def get(self,request):

        #获取前段传递的state
        next = request.query_params.get('state',None)
        if not next :
            next = '/'
        #初始化连接对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        #构造qq登陆跳转连接
        login_url=oauth.get_qq_url()
        # print(login_url)
        #返回结果(五个拓展类并不满足需求)
        return Response({'login_url':login_url})




class QQAuthUserView(CreateAPIView): #五个拓展类并不满足需求
    serializer_class =QQAuthUserSerializer
    def get(self,request):

        #获取code
        code = request.query_params.get('code',None)
        #验证code
        if not code:
            return Response({'error':'缺少code'})

        #通过code获取assess_token
        state = '/'
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        access_token = oauth.get_access_token(code)
        #通过assess_token获取openid
        openid = oauth.get_open_id(access_token)
        #判断是否绑定美多用户
        try:
            qq_user=OAuthQQUser.objects.get(openid=openid)
        except:
            #未绑定,meiduo_mall@localhost
            #加密openoid
            tjs = TJS(settings.SECRET_KEY,300)
            open_id = tjs.dumps({'openid':openid}).decode()
            return Response({'access_token':open_id})
        else:
            #绑定
            #登陆成功
            #获取用户对象
            user=qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)  # 保存到载荷部分
            token = jwt_encode_handler(payload)  # 生成TOKEN

            return Response({
        'token':token,
        'username':user.username,
        'user_id':user.id
    })
        #返回结果


